package com.mls.fivedistrict.server.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.github.pagehelper.util.StringUtil;
import com.mls.fivedistrict.common.PageFilter;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.dao.IntegralMapper;
import com.mls.fivedistrict.dao.ReportMapper;
import com.mls.fivedistrict.pojo.*;
import com.mls.fivedistrict.server.ReportService;
import com.mls.fivedistrict.server.UserService;
import com.mls.fivedistrict.server.WithdrawRecordService;
import com.mls.fivedistrict.util.TimeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by nanji on 2018/3/21.
 */
@Service("reportService")
public class ReportServiceImpl implements ReportService {
    @Resource(name = "reportMapper")
    ReportMapper reportMapper;
    @Resource(name = "userService")
    UserService userService;
    @Resource(name = "integralMapper")
    IntegralMapper integralMapper;
    @Resource(name = "withdrawRecordService")
    WithdrawRecordService withdrawRecordService;

    @Override
    public ServiceResponse TotalEveryDay(PageFilter pageFilter) {
        Map<String, Date> maps = new HashMap<>();
        if (pageFilter.getFilterMap() != null && pageFilter.getFilterMap().size() > 0) {
            if (!StringUtils.isEmpty(pageFilter.getFilterMap().get("start"))) {
//                maps.put("start", new Date(Long.parseLong(pageFilter.getFilterMap().get("start").trim())));
                maps.put("start", TimeUtils.millis2Date(Long.parseLong(pageFilter.getFilterMap().get("start").trim())));
            }
            if (!StringUtils.isEmpty(pageFilter.getFilterMap().get("end"))) {
                Date end = new Date(Long.parseLong(pageFilter.getFilterMap().get("end").toString()) + 24 * 60 * 60 * 1000 - 1);
//                Calendar calendar = new GregorianCalendar();
//                calendar.setTime(end);
//                calendar.add(Calendar.DAY_OF_MONTH, 1);
//                end = calendar.getTime();
                maps.put("end", end);
            }
        }
        List<Report> reports = reportMapper.getEveryUserReport(maps);
        PageInfo<Report> pageInfo = new PageInfo<>(reports);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }

    /**
     * 根据搜索条件，获取用户的积分报表
     *
     * @param pageFilter
     * @return
     */
    @Override
    public ServiceResponse getUserIntegralReports(PageFilter pageFilter) {
        Map<String, String> maps = pageFilter.getFilterMap();
        Map<String, Object> params = new HashMap<>();
        maps.forEach((k, v) -> {
            if (!StringUtil.isEmpty(v)) {
                if (k.equals("startDate") || k.equals("endDate")) {
                    params.put(k, TimeUtils.millis2Date(Long.parseLong(v)));
                } else {
                    params.put(k, v);
                }
            }
        });
        Object phone = params.get("phone");
        if (phone != null) {
            User user = userService.getUserByPhone(phone.toString().trim());
            if (user == null) {
                return ServiceResponse.createErrorResponse("没有此电话号码!");
            }
            params.put("user_id", user.getId() + "");
            params.remove("phone");
        }
        List<Record> userIntegralReportList = new ArrayList<>();
        int recordCount = reportMapper.getUserIntegralReportsCount(params);
        int receiveRecordCount = reportMapper.getUserIntegralReceiverReportsCount(params);
        int count = recordCount + receiveRecordCount;
        int startIndex = (pageFilter.getPageNum() - 1) * pageFilter.getPageSize();
        int endIndex = startIndex + pageFilter.getPageSize();
        if (recordCount >= endIndex) {
            params.put("startIndex", startIndex);
            params.put("dataSize", pageFilter.getPageSize());
            userIntegralReportList = reportMapper.getUserIntegralReports(params);
        } else if (recordCount > startIndex && endIndex > recordCount) {
            params.put("startIndex", startIndex);
            params.put("dataSize", pageFilter.getPageSize());
            userIntegralReportList = reportMapper.getUserIntegralReports(params);
            params.put("startIndex", 0);
            params.put("dataSize", pageFilter.getPageSize() - userIntegralReportList.size());
            List<Record> userIntegralReceiveReportList = reportMapper.getUserIntegralReceiverReports(params);
            userIntegralReportList.addAll(userIntegralReceiveReportList);
        } else if (recordCount <= startIndex && count > startIndex) {
            params.put("startIndex", startIndex - recordCount);
            params.put("dataSize", pageFilter.getPageSize());
            userIntegralReportList = reportMapper.getUserIntegralReceiverReports(params);
        }
        Page pages = new Page();
        for (Record r : userIntegralReportList) {
            pages.add(r);
        }
        pages.setTotal(count);
        pages.setPageNum(pageFilter.getPageNum());
        double p = Math.ceil(count * 1.0 / pageFilter.getPageSize());
        pages.setPages((int) p);
        PageInfo pageInfo = new PageInfo(pages, 8);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }

    /**
     * 根据搜索条件，获取用户的所有积分总和
     *
     * @param pageFilter
     * @return
     */
    @Override
    public ServiceResponse getSumUserIntegralReports(PageFilter pageFilter) {
        Map<String, String> maps = pageFilter.getFilterMap();
        Map<String, Object> params = new HashMap<>();
        maps.forEach((k, v) -> {
            if (!StringUtil.isEmpty(v)) {
                if (k.equals("startDate") || k.equals("endDate")) {
                    params.put(k, TimeUtils.millis2Date(Long.parseLong(v)));
                } else {
                    params.put(k, v);
                }
            }
        });
        Object phone = params.get("phone");
        if (phone != null) {
            User user = userService.getUserByPhone(phone.toString().trim());
            if (user == null) {
                return ServiceResponse.createErrorResponse("没有此电话号码!");
            }
            params.put("user_id", user.getId() + "");
            params.remove("phone");
        }
        double sum = reportMapper.getSumUserIntegralReports(params);
        return ServiceResponse.createSuccessResponse(sum);
    }

    /**
     * 获取用户的算力报表
     *
     * @param pageFilter
     * @return
     */
    @Override
    public ServiceResponse getUserCalculateReports(PageFilter pageFilter) {
        Map<String, String> maps = pageFilter.getFilterMap();
        Map<String, Object> params = new HashMap<>();
        maps.forEach((k, v) -> {
            if (!StringUtil.isEmpty(v)) {
                if (k.equals("startDate") || k.equals("endDate")) {
//                    params.put(k, new Date(Long.parseLong(v)).toLocaleString());
                    params.put(k, TimeUtils.millis2Date(Long.parseLong(v)));
                } else {
                    params.put(k, v);
                }
            }
        });
        Object phone = params.get("phone");
        if (phone != null) {
            User user = userService.getUserByPhone(phone.toString().trim());
            if (user == null) {
                return ServiceResponse.createErrorResponse("没有此电话号码!");
            }
            params.put("user_id", user.getId() + "");
            params.remove("phone");
        }
        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        List<RecordUserCalculate> recordUserCalculateList = reportMapper.getUserCalculateReports(params);
        PageInfo<RecordUserCalculate> pageInfo = new PageInfo<>(recordUserCalculateList);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }

    /**
     * 根据搜索条件，获取用户的算力总和
     *
     * @param pageFilter
     * @return
     */
    @Override
    public ServiceResponse getSumUserCalculateReports(PageFilter pageFilter) {
        Map<String, String> maps = pageFilter.getFilterMap();
        Map<String, Object> params = new HashMap<>();
        maps.forEach((k, v) -> {
            if (!StringUtil.isEmpty(v)) {
                if (k.equals("startDate") || k.equals("endDate")) {
                    params.put(k, TimeUtils.millis2Date(Long.parseLong(v)));
                } else {
                    params.put(k, v);
                }
            }
        });
        Object phone = params.get("phone");
        if (phone != null) {
            User user = userService.getUserByPhone(phone.toString().trim());
            if (user == null) {
                return ServiceResponse.createErrorResponse("没有此电话号码!");
            }
            params.put("user_id", user.getId() + "");
            params.remove("phone");
        }
        double sum = reportMapper.getSumUserCalculateReports(params);
        return ServiceResponse.createSuccessResponse(sum);
    }

    /**
     * 根据搜索条件获取用户的总记录数
     *
     * @param pageFilter
     * @return
     */
    @Override
    public ServiceResponse getUserTaskReports(PageFilter pageFilter) {
        Map<String, String> maps = pageFilter.getFilterMap();
        Map<String, Object> params = new HashMap<>();
        maps.forEach((k, v) -> {
            if (!StringUtil.isEmpty(v)) {
                if (k.equals("startDate") || k.equals("endDate")) {
                    params.put(k, TimeUtils.millis2Date(Long.parseLong(v)));
                } else {
                    params.put(k, v);
                }
            }
        });

        Object phone = params.get("phone");
        if (phone != null) {
            User user = userService.getUserByPhone(phone.toString().trim());
            if (user == null) {
                return ServiceResponse.createErrorResponse("没有此电话号码!");
            }
            params.put("user_id", user.getId() + "");
            params.remove("phone");
        }

        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        List<RecordUserTask> recordUserTaskList = reportMapper.getUserTaskReports(params);
        PageInfo pageInfo = new PageInfo(recordUserTaskList);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }

    /**
     * 获取用户的提取报表信息
     *
     * @param pageFilter
     * @return
     */
    @Override
    public ServiceResponse getUserIntegralExtractReports(PageFilter pageFilter) {
        Map<String, String> maps = new HashMap<>();
        pageFilter.getFilterMap().forEach((k, v) -> {
            if (!StringUtils.isEmpty(v)) {
                maps.put(k, v);
            }
        });
        pageFilter.setFilterMap(maps);
        List<WithdrawRecord> withdrawRecords = withdrawRecordService.getWithdrawRecordList(pageFilter);
        PageInfo pageInfo = new PageInfo(withdrawRecords);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }

    @Override
    public ServiceResponse getDwqMineSum() {
        double dwqMineSum = reportMapper.getDwqUserSum();
        return ServiceResponse.createSuccessResponse(dwqMineSum);
    }


    @Override
    public ServiceResponse getUserPropertyReports(PageFilter pageFilter) {
        Map<String, String> maps = pageFilter.getFilterMap();
        Map<String, Object> params = new HashMap<>();
        maps.forEach((k, v) -> {
            if (!StringUtil.isEmpty(v)) {
                params.put(k, v);
            }
        });

        Object phone = params.get("phone");
        if (phone != null) {
            User user = userService.getUserByPhone(phone.toString().trim());
            if (user == null) {
                return ServiceResponse.createErrorResponse("没有此电话号码!");
            }
            params.put("user_id", user.getId() + "");
            params.remove("phone");
        }
        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        List<Property> propertyList = reportMapper.getUserPropertyReports(params);

        PageInfo pageInfo = new PageInfo(propertyList);
        return ServiceResponse.createSuccessResponse(pageInfo);
    }

    @Override
    public ServiceResponse getSumUserPropertyReports(PageFilter pageFilter) {
        Map<String, String> maps = pageFilter.getFilterMap();
        Map<String, Object> params = new HashMap<>();
        maps.forEach((k, v) -> {
            if (!StringUtil.isEmpty(v)) {
                params.put(k, v);
            }
        });

        Object phone = params.get("phone");
        if (phone != null) {
            User user = userService.getUserByPhone(phone.toString().trim());
            if (user == null) {
                return ServiceResponse.createErrorResponse("没有此电话号码!");
            }
            params.put("user_id", user.getId() + "");
            params.remove("phone");
        }

        double propertySum = reportMapper.getSumUserPropertyReports(params);
        return ServiceResponse.createSuccessResponse(propertySum);
    }

    @Override
    public ServiceResponse getSumUserIntegralExtractReports(PageFilter pageFilter) {
        Map<String, String> maps = new HashMap<>();
        pageFilter.getFilterMap().forEach((k, v) -> {
            if (!StringUtils.isEmpty(v)) {
                maps.put(k, v);
            }
        });
        pageFilter.setFilterMap(maps);
        double withdrawRecordSum = withdrawRecordService.getWithdrawRecordSum(pageFilter);
        return ServiceResponse.createSuccessResponse(withdrawRecordSum);
    }


}
